var App = function () {

	var currentPage = ''; // Trang hien tai
	var collapsed = false; //Chuyen doi sidebar
	var is_mobile = false; //Manf hinh mobile?
	var is_mini_menu = false; //minu-menu duoc kich hoat
	var is_fixed_header = false; //co dinh header duoc kich hoat
	var responsiveFunctions = []; //ham responsive
	
	/*-----------------------------------------------------------------------------------*/
    /*  Chay cac ham callback bang cach thiet lap App.addResponsiveFunction()
    /*-----------------------------------------------------------------------------------*/
    var runResponsiveFunctions = function () {
        // khoi tao lai cac thanh phan da duoc dang ky khac
        for (var i in responsiveFunctions) {
            var each = responsiveFunctions[i];
            each.call();
        }
    }
    /*-----------------------------------------------------------------------------------*/
    /*  Lay do rong viewport chinh xac dua tren http://andylangton.co.uk/articles/javascript/get-viewport-size-javascript/
    /*-----------------------------------------------------------------------------------*/
    var getViewPort = function () {
        var e = window, a = 'inner';
        if (!('innerWidth' in window)) {
            a = 'client';
            e = document.documentElement || document.body;
        }
        return {
            width: e[a + 'Width'],
            height: e[a + 'Height']
        }
    }
    /*-----------------------------------------------------------------------------------*/
    /*  kiem tra kich co layout
    /*-----------------------------------------------------------------------------------*/
    var checkLayout = function() {
        //Kiem tra neu sidebar la mini-menu
        is_mini_menu = $('#sidebar').hasClass('mini-menu');
        //Kiem tra neu header duoc kich hoat che do co dinh
        is_fixed_header = $('#header').hasClass('navbar-fixed-top');
    }
    /*-----------------------------------------------------------------------------------*/
    /*  Sidebar & Main Content size match
    /*-----------------------------------------------------------------------------------*/
    var handleSidebarAndContentHeight = function () {
        var content = $('#content');
        var sidebar = $('#sidebar');
        var body = $('body');
        var height;

        if (body.hasClass('sidebar-fixed')) {
            height = $(window).height() - $('#header').height() + 1;
        } else {
            height = sidebar.height() + 20;
        }
        if (height >= content.height()) {
            content.attr('style', 'min-height:' + height + 'px !important');
        }
    }
    /*-----------------------------------------------------------------------------------*/
    /*  Sidebar
    /*-----------------------------------------------------------------------------------*/
    var handleSidebar = function () {
    jQuery('.sidebar-menu .has-sub > a').click(function () {
            var last = jQuery('.has-sub.open', $('.sidebar-menu'));
            last.removeClass("open");
            jQuery('.arrow', last).removeClass("open");
            jQuery('.sub', last).slideUp(200);
            
            var thisElement = $(this);
            var slideOffeset = -200;
            var slideSpeed = 200;
            
            var sub = jQuery(this).next();
            if (sub.is(":visible")) {
                jQuery('.arrow', jQuery(this)).removeClass("open");
                jQuery(this).parent().removeClass("open");
                sub.slideUp(slideSpeed, function () {
                    if ($('#sidebar').hasClass('sidebar-fixed') == false) {
                        App.scrollTo(thisElement, slideOffeset);
                    }
                    handleSidebarAndContentHeight();
                });
            } else {
                jQuery('.arrow', jQuery(this)).addClass("open");
                jQuery(this).parent().addClass("open");
                sub.slideDown(slideSpeed, function () {
                    if ($('#sidebar').hasClass('sidebar-fixed') == false) {
                        App.scrollTo(thisElement, slideOffeset);
                    }
                    handleSidebarAndContentHeight();
                });
            }
        });
        
    // Thuc thi cac menu con
    jQuery('.sidebar-menu .has-sub .sub .has-sub-sub > a').click(function () {
            var last = jQuery('.has-sub-sub.open', $('.sidebar-menu'));
            last.removeClass("open");
            jQuery('.arrow', last).removeClass("open");
            jQuery('.sub', last).slideUp(200);
                
            var sub = jQuery(this).next();
            if (sub.is(":visible")) {
                jQuery('.arrow', jQuery(this)).removeClass("open");
                jQuery(this).parent().removeClass("open");
                sub.slideUp(200);
            } else {
                jQuery('.arrow', jQuery(this)).addClass("open");
                jQuery(this).parent().addClass("open");
                sub.slideDown(200);
            }
        });
    }
    
    /*-----------------------------------------------------------------------------------*/
    /* Chuyen doi sidebar tu dong
    /*-----------------------------------------------------------------------------------*/
    var collapseSidebar = function () {
        var iconElem = document.getElementById("sidebar-collapse").querySelector('[class*="fa-"]');
        var iconLeft = iconElem.getAttribute("data-icon1");
        var iconRight = iconElem.getAttribute("data-icon2");
        /* Cho Navbar */
        jQuery('.navbar-brand').addClass("mini-menu");
        /* Cho sidebar */
        jQuery('#sidebar').addClass("mini-menu");
        jQuery('#main-content').addClass("margin-left-50");
        jQuery('.sidebar-collapse i').removeClass(iconLeft);
        jQuery('.sidebar-collapse i').addClass(iconRight);
        /* Loai bo placeholder tu Search Bar */
        jQuery('.search').attr('placeholder', '');
        collapsed = true;
        /* Set a cookie so that mini-sidebar persists */
        $.cookie('mini_sidebar', '1');
    }
    /*-----------------------------------------------------------------------------------*/
    /*  Responsive Sidebar Collapse
    /*-----------------------------------------------------------------------------------*/
    var responsiveSidebar = function () {
        //Handle sidebar collapse on screen width
        var width = $(window).width();
        if ( width < 768 ) {
            is_mobile = true;
            //Hide the sidebar completely
            jQuery('#main-content').addClass("margin-left-0");
        }
        else {
            is_mobile = false;
            //Show the sidebar completely
            jQuery('#main-content').removeClass("margin-left-0");
            var menu = $('.sidebar');
            if (menu.parent('.slimScrollDiv').size() === 1) { // destroy existing instance before resizing
                menu.slimScroll({
                    destroy: true
                });
                menu.removeAttr('style');
                $('#sidebar').removeAttr('style');
            }
        }
    }
    /*-----------------------------------------------------------------------------------*/
    /*  Sidebar Collapse
    /*-----------------------------------------------------------------------------------*/
    var handleSidebarCollapse = function () {
        var viewport = getViewPort();
        if ($.cookie('mini_sidebar') === '1') {
            /* For Navbar */
            jQuery('.navbar-brand').addClass("mini-menu");
            /* For sidebar */
            jQuery('#sidebar').addClass("mini-menu");
            jQuery('#main-content').addClass("margin-left-50");
            collapsed = true;
        }
        //Handle sidebar collapse on user interaction
        jQuery('.sidebar-collapse').click(function () {
            //Handle mobile sidebar toggle
            if(is_mobile && !(is_mini_menu)){
                //If sidebar is collapsed
                if(collapsed){
                    jQuery('body').removeClass("slidebar");
                    jQuery('.sidebar').removeClass("sidebar-fixed");
                    //Add fixed top nav if exists
                    if(is_fixed_header) {
                        jQuery('#header').addClass("navbar-fixed-top");
                        jQuery('#main-content').addClass("margin-top-100");
                    }
                    collapsed = false;
                    $.cookie('mini_sidebar', '0');
                }
                else {
                    jQuery('body').addClass("slidebar");
                    jQuery('.sidebar').addClass("sidebar-fixed");
                    //Remove fixed top nav if exists
                    if(is_fixed_header) {
                        jQuery('#header').removeClass("navbar-fixed-top");
                        jQuery('#main-content').removeClass("margin-top-100");
                    }
                    collapsed = true;
                    $.cookie('mini_sidebar', '1');
                    handleMobileSidebar();
                }
            }
            else { //Handle regular sidebar toggle
                var iconElem = document.getElementById("sidebar-collapse").querySelector('[class*="fa-"]');
                var iconLeft = iconElem.getAttribute("data-icon1");
                var iconRight = iconElem.getAttribute("data-icon2");
                //If sidebar is collapsed
                if(collapsed){
                    /* For Navbar */
                    jQuery('.navbar-brand').removeClass("mini-menu");
                    /* For sidebar */
                    jQuery('#sidebar').removeClass("mini-menu");
                    jQuery('#main-content').removeClass("margin-left-50");
                    jQuery('.sidebar-collapse i').removeClass(iconRight);
                    jQuery('.sidebar-collapse i').addClass(iconLeft);
                    /* Add placeholder from Search Bar */
                    jQuery('.search').attr('placeholder', "Search");
                    collapsed = false;
                    $.cookie('mini_sidebar', '0');
                }
                else {
                    /* For Navbar */
                    jQuery('.navbar-brand').addClass("mini-menu");
                    /* For sidebar */
                    jQuery('#sidebar').addClass("mini-menu");
                    jQuery('#main-content').addClass("margin-left-50");
                    jQuery('.sidebar-collapse i').removeClass(iconLeft);
                    jQuery('.sidebar-collapse i').addClass(iconRight);
                    /* Remove placeholder from Search Bar */
                    jQuery('.search').attr('placeholder', '');
                    collapsed = true;
                    $.cookie('mini_sidebar', '1');
                }
                $("#main-content").on('resize', function (e) {
                    e.stopPropagation();
                });
            }
        });
    }
    /*-----------------------------------------------------------------------------------*/
    /*  Handle Fixed Sidebar on Mobile devices
    /*-----------------------------------------------------------------------------------*/
    var handleMobileSidebar = function () {
        var menu = $('.sidebar');
        if (menu.parent('.slimScrollDiv').size() === 1) { // destroy existing instance before updating the height
            menu.slimScroll({
                destroy: true
            });
            menu.removeAttr('style');
            $('#sidebar').removeAttr('style');
        }
        menu.slimScroll({
            size: '7px',
            color: '#a1b2bd',
            opacity: .3,
            height: "100%",
            allowPageScroll: false,
            disableFadeOut: false
        });
    }
    /*-----------------------------------------------------------------------------------*/
    /*  Handle Fixed Sidebar
    /*-----------------------------------------------------------------------------------*/
    var handleFixedSidebar = function () {
        var menu = $('.sidebar-menu');

        if (menu.parent('.slimScrollDiv').size() === 1) { // destroy existing instance before updating the height
            menu.slimScroll({
                destroy: true
            });
            menu.removeAttr('style');
            $('#sidebar').removeAttr('style');
        }

        if ($('.sidebar-fixed').size() === 0) {
            handleSidebarAndContentHeight();
            return;
        }

        var viewport = getViewPort();
        if (viewport.width >= 992) {
            var sidebarHeight = $(window).height() - $('#header').height() + 1;

            menu.slimScroll({
                size: '7px',
                color: '#a1b2bd',
                opacity: .3,
                height: sidebarHeight,
                allowPageScroll: false,
                disableFadeOut: false
            });
            handleSidebarAndContentHeight();
        }
    }
    /*-----------------------------------------------------------------------------------*/
    /*  Handles navbar fixed top
    /*-----------------------------------------------------------------------------------*/
    var handleNavbarFixedTop = function () {
        if(is_mobile && is_fixed_header) {
            //Manage margin top
            $('#main-content').addClass('margin-top-100');
        }
        if(!(is_mobile) && is_fixed_header){
            //Manage margin top
            $('#main-content').removeClass('margin-top-100').addClass('margin-top-50');
        }
    }
    /*-----------------------------------------------------------------------------------*/
    /*  Windows Resize function
    /*-----------------------------------------------------------------------------------*/
    jQuery(window).resize(function() {
        setTimeout(function () {
            checkLayout();
            handleSidebarAndContentHeight();
            responsiveSidebar();
            handleFixedSidebar();
            handleNavbarFixedTop();
            runResponsiveFunctions(); 
        }, 50); // wait 50ms until window resize finishes.
    });

    /*-----------------------------------------------------------------------------------*/
    /*  Team View
    /*-----------------------------------------------------------------------------------*/
    var handleTeamView = function () {
        c();
        $(".team-status-toggle").click(function (y) {
            y.preventDefault();
            w(this);
            $(this).parent().toggleClass("open");
            var z = x(this);
            $(z).slideToggle(200, function () {
                $(this).toggleClass("open")
            })
        });
        $("body").click(function (z) {
            var y = z.target.className.split(" ");
            if ($.inArray("team-status", y) == -1 && $.inArray("team-status-toggle", y) == -1 && $(z.target).parents().index($(".team-status")) == -1 && $(z.target).parents(".team-status-toggle").length == 0) {
                w()
            }
        });
        $(".team-status #teamslider").each(function () {
            $(this).slimScrollHorizontal({
                width: "100%",
                alwaysVisible: true,
                color: "#fff",
                opacity: "0.5",
                size: "5px"
            })
        });
        var w = function (y) {
            $(".team-status").each(function () {
                var z = $(this);
                if (z.is(":visible")) {
                    var A = x(y);
                    if (A != ("#" + z.attr("id"))) {
                        $(this).slideUp(200, function () {
                            $(this).toggleClass("open");
                            $(".team-status-toggle").each(function () {
                                var B = x(this);
                                if (B == ("#" + z.attr("id"))) {
                                    $(this).parent().removeClass("open")
                                }
                            })
                        })
                    }
                }
            })
        };
        var x = function (y) {
            var z = $(y).data("teamStatus");
            if (typeof z == "undefined") {
                z = "#team-status"
            }
            return z
        }
    }
    var c = function () {
        $(".team-status").each(function () {
            var x = $(this);
            x.css("position", "absolute").css("margin-top", "-1000px").show();
            var w = 0;
            $("ul li", this).each(function () {
                w += $(this).outerWidth(true) + 15
            });
            x.css("position", "relative").css("margin-top", "0").hide();
            $("ul", this).width(w)
        })
    };
    /*-----------------------------------------------------------------------------------*/
    /*  Homepage tooltips
    /*-----------------------------------------------------------------------------------*/
    var handleHomePageTooltips = function () {
        //On Hover
        //Default tooltip (Top)
        $('.tip').tooltip();
        //Bottom tooltip
        $('.tip-bottom').tooltip({
            placement : 'bottom'
        });
        //Left tooltip
        $('.tip-left').tooltip({
            placement : 'left'
        });
        //Right tooltip
        $('.tip-right').tooltip({
            placement : 'right'
        });
        //On Focus
        //Default tooltip (Top)
        $('.tip-focus').tooltip({
            trigger: 'focus'
        });
    }

    /*-----------------------------------------------------------------------------------*/
    /* Box tools
    /*-----------------------------------------------------------------------------------*/
    var handleBoxTools = function () {
        //Collapse
        jQuery('.box .tools .collapse, .box .tools .expand').click(function () {
            var el = jQuery(this).parents(".box").children(".box-body");
            if (jQuery(this).hasClass("collapse")) {
                jQuery(this).removeClass("collapse").addClass("expand");
                var i = jQuery(this).children(".fa-chevron-up");
                i.removeClass("fa-chevron-up").addClass("fa-chevron-down");
                el.slideUp(200);
            } else {
                jQuery(this).removeClass("expand").addClass("collapse");
                var i = jQuery(this).children(".fa-chevron-down");
                i.removeClass("fa-chevron-down").addClass("fa-chevron-up");
                el.slideDown(200);
            }
        });
        
        /* Close */
        jQuery('.box .tools a.remove').click(function () {
            var removable = jQuery(this).parents(".box");
            if (removable.next().hasClass('box') || removable.prev().hasClass('box')) {
                jQuery(this).parents(".box").remove();
            } else {
                jQuery(this).parents(".box").parent().remove();
            }
        });
        
        /* Reload */
        jQuery('.box .tools a.reload').click(function () {
            var el = jQuery(this).parents(".box");
            App.blockUI(el);
            window.setTimeout(function () {
                App.unblockUI(el);
            }, 1000);
        });
    }
    /*-----------------------------------------------------------------------------------*/
    /*  SlimScroll
    /*-----------------------------------------------------------------------------------*/
    var handleSlimScrolls = function () {
        if (!jQuery().slimScroll) {
            return;
        }

        $('.scroller').each(function () {
            $(this).slimScroll({
                size: '7px',
                color: '#a1b2bd',
                height: $(this).attr("data-height"),
                alwaysVisible: ($(this).attr("data-always-visible") == "1" ? true : false),
                railVisible: ($(this).attr("data-rail-visible") == "1" ? true : false),
                railOpacity: 0.1,
                disableFadeOut: true
            });
        });
    }
    
    /*-----------------------------------------------------------------------------------*/
    /*  Bootbox alerts
    /*-----------------------------------------------------------------------------------*/
    var handleBootbox = function () {
        $(".basic-alert").click(function(){
            bootbox.alert("Hello World");
        });
        $(".confirm-dialog").click(function(){
            bootbox.confirm("Are you sure?", function(result){});
        });
        $(".multiple-buttons").click(function(){
            bootbox.dialog({
            message: "I am a custom dialog",
            title: "Custom title",
            buttons: {
                success: {
                    label: "Success!",
                    className: "btn-success",
                    callback: function() {
                    Example.show("great success");
                    }
                },
                danger: {
                    label: "Danger!",
                    className: "btn-danger",
                    callback: function() {
                    Example.show("uh oh, look out!");
                    }
                },
                main: {
                    label: "Click ME!",
                    className: "btn-primary",
                    callback: function() {
                    Example.show("Primary button");
                    }
                }
            }
            });
        });
        $(".multiple-dialogs").click(function(){
            bootbox.alert("In 1 second a new modal will open");
            setTimeout(function() {
                bootbox.dialog({
            message: "Will you purchase this awesome theme",
            title: "Pop quiz",
            buttons: {
                success: {
                    label: "Yes!",
                    className: "btn-success",
                    callback: function() {
                        bootbox.alert("Congratulations! You made the right decision.", function(){
                            $(".bootbox").modal("hide");
                        });
                    }
                },
                danger: {
                    label: "No!",
                    className: "btn-danger",
                    callback: function() {
                        bootbox.alert("Oops, we're sorry to hear that!", function(){
                            $(".bootbox").modal("hide");
                        });
                        
                    }
                },
                main: {
                    label: "Click ME!",
                    className: "btn-primary",
                    callback: function() {
                        bootbox.alert("Hello World", function(){
                            $(".bootbox").modal("hide");
                        });
                    }
                }
            }
            });
            }, 1000);
        });
        $(".programmatic-close").click(function(){
            bootbox.alert("In 3 second this modal will close..");
            setTimeout(function() {
                $(".bootbox").modal("hide");
            }, 3000);
        });
        
    }
    /*-----------------------------------------------------------------------------------*/
    /*  Popovers
    /*-----------------------------------------------------------------------------------*/
    var handlePopovers = function () {
        //Default (Right)
        $('.pop').popover();
        //Bottom 
        $('.pop-bottom').popover({
            placement : 'bottom'
        });
        //Left 
        $('.pop-left').popover({
            placement : 'left'
        });
        //Top 
        $('.pop-top').popover({
            placement : 'top'
        });
        //Trigger hover 
        $('.pop-hover').popover({
            trigger: 'hover'
        });
    }
    
    /*-----------------------------------------------------------------------------------*/
    /*  Hubspot messenger
    /*-----------------------------------------------------------------------------------*/
    var handleMessenger = function () {
        
        //Normal
        $("#normal").click(function(){
            var mytheme = $('input[name=theme]:checked').val();
            var mypos = $('input[name=position]:checked').val();
            //Set theme
            Messenger.options = {
                extraClasses: 'messenger-fixed '+mypos,
                theme: mytheme
            }
            //Call
            Messenger().post({
                message:"This is a normal notification!",
                showCloseButton: true
            });
        });
        //Interactive
        $("#interactive").click(function(){
            var mytheme = $('input[name=theme]:checked').val();
            var mypos = $('input[name=position]:checked').val();
            //Set theme
            Messenger.options = {
                extraClasses: 'messenger-fixed '+mypos,
                theme: mytheme
            }
            var msg;
            msg = Messenger().post({
              message: 'Launching thermonuclear war...',
              type: 'info',
              actions: {
                cancel: {
                  label: 'cancel launch',
                  action: function() {
                    return msg.update({
                      message: 'Thermonuclear war averted',
                      type: 'success',
                      showCloseButton: true,
                      actions: false
                    });
                  }
                }
              }
            });
        });
        //Timer
        $("#timer").click(function(){
            var mytheme = $('input[name=theme]:checked').val();
            var mypos = $('input[name=position]:checked').val();
            //Set theme
            Messenger.options = {
                extraClasses: 'messenger-fixed '+mypos,
                theme: mytheme
            }
            var i;
            i = 0;
            Messenger().run({
              errorMessage: 'Error destroying alien planet',
              successMessage: 'Alien planet destroyed!',
              showCloseButton: true,
              action: function(opts) {
                if (++i < 3) {
                  return opts.error({
                    status: 500,
                    readyState: 0,
                    responseText: 0
                  });
                } else {
                  return opts.success();
                }
              }
            });
        });
        //Prompts
        $("#prompts").click(function(){
            var mytheme = $('input[name=theme]:checked').val();
            var mypos = $('input[name=position]:checked').val();
            //Set theme
            Messenger.options = {
                extraClasses: 'messenger-fixed '+mypos,
                theme: mytheme
            }
            Messenger().run({
              successMessage: 'Data saved.',
              errorMessage: 'Error saving data',
              progressMessage: 'Saving data',
              showCloseButton: true,
            }, {
              url: 'http://www.example.com/data'
            });
        });
    }
    /*-----------------------------------------------------------------------------------*/
    /*  Alerts
    /*-----------------------------------------------------------------------------------*/
    var handleAlerts = function () {
        $(".alert").alert();
    }

    /*-----------------------------------------------------------------------------------*/
    /*  Custom tabs
    /*-----------------------------------------------------------------------------------*/
    var handleCustomTabs = function () {
            var adjustMinHeight = function (y) {
                $(y).each(function () {
                    var A = $($($(this).attr("href")));
                    var z = $(this).parent().parent();
                    if (z.height() > A.height()) {
                        A.css("min-height", z.height())
                    }
                })
            };
            $("body").on("click", '.nav.nav-tabs.tabs-left a[data-toggle="tab"], .nav.nav-tabs.tabs-right a[data-toggle="tab"]', function () {
                adjustMinHeight($(this));
            });
            adjustMinHeight('.nav.nav-tabs.tabs-left > li.active > a[data-toggle="tab"], .nav.nav-tabs.tabs-right > li.active > a[data-toggle="tab"]');

        $("body").on("click", 'a[data-toggle="tab"]', function () {
            window.location.hash = $(this).attr('href');
        });

        if (location.hash) {
            var w = location.hash.substr(1);
            $('a[href="#' + w + '"]').click()
        }

    }

    /*-----------------------------------------------------------------------------------*/
    /*  Handles the go to top button at the footer
    /*-----------------------------------------------------------------------------------*/
    var handleGoToTop = function () {
        $('.footer-tools').on('click', '.go-top', function (e) {
            App.scrollTo();
            e.preventDefault();
        });
    } 

    /* For Home Page */
	/*-----------------------------------------------------------------------------------*/
    /*  Date Range Picker
    /*-----------------------------------------------------------------------------------*/
    var handleDateTimePickers = function () {

        $('#reportrange').daterangepicker(
            {
               startDate: moment().subtract('ngày', 29),
               endDate: moment(),
               minDate: '01/01/2012',
               maxDate: '31/12/2014',
               dateLimit: { days: 60 },
               showDropdowns: true,
               showWeekNumbers: true,
               timePicker: false,
               timePickerIncrement: 1,
               timePicker12Hour: true,
               ranges: {
                  'Hôm qua': [moment().subtract('ngày', 1), moment().subtract('ngày', 1)],
                  '30 ngày trước': [moment().subtract('ngày', 29), moment()],
                  'Tháng này': [moment().startOf('tháng'), moment().endOf('tháng')]
               },
               opens: 'left',
               buttonClasses: ['btn btn-default'],
               applyClass: 'btn-small btn-primary',
               cancelClass: 'btn-small',
               format: 'DD/MM/YYYY',
               separator: ' tới ',
               locale: {
                   applyLabel: 'Chọn',
                   fromLabel: 'Từ',
                   toLabel: 'Đến',
                   customRangeLabel: 'Vùng tùy chọn',
                   daysOfWeek: ['CN', 'T2', 'T3', 'T4', 'T5', 'T6','T7'],
                   monthNames: ['Tháng 1', 'Tháng 2', 'Tháng 3', 'Tháng 4', 'Tháng 4', 'Tháng 6', 'Tháng 7', 'Tháng 8', 'Tháng 9', 'Tháng 10', 'Tháng 11', 'Tháng 12'],
                   firstDay: 1
               }
            },
            function(start, end) {
             console.log("Callback has been called!");
             $('#reportrange span').html(start.format('D MMMM, YYYY') + ' - ' + end.format('D MMMM, YYYY'));
            }
         );
         //Set the initial state of the picker label
         $('#reportrange span').html('Custom');
    }

    /*-----------------------------------------------------------------------------------*/
    /*  Sparklines
    /*-----------------------------------------------------------------------------------*/
    var handleSparkline = function () {
        //Sparkline bar
        $(".sparkline").each(function() {
          var barSpacing, barWidth, color, height;
          color = $(this).attr("data-color") || "white";
          height = "18px";
          if ($(this).hasClass("big")) {
            barWidth = "5px";
            barSpacing = "2px";
            height = "40px";
          }
          return $(this).sparkline("html", {
            type: "bar",
            barColor: Theme.colors[color],
            height: height,
            barWidth: barWidth,
            barSpacing: barSpacing,
            zeroAxis: false
          });
        });
        //Sparkline Pie
        $(".sparklinepie").each(function() {
          var height;
          height = "50px";
          if ($(this).hasClass("big")) {
            height = "70px";
          }
          return $(this).sparkline("html", {
            type: "pie",
            height: height,
            sliceColors: [Theme.colors.blue, Theme.colors.red, Theme.colors.green, Theme.colors.orange]
          });
        });
        //Sparkline Line
        $(".linechart").each(function() {
          var height;
          height = "18px";
          if ($(this).hasClass("linechart-lg")) {
            height = "30px";
          }
          return $(this).sparkline("html", {
            type: "line",
            height: height,
            width: "150px",
            minSpotColor: Theme.colors.red,
            maxSpotColor: Theme.colors.green,
            spotRadius: 3,
            lineColor: Theme.colors.primary,
            fillColor: "rgba(94,135,176,0.1)",
            lineWidth: 1.2,
            highlightLineColor: Theme.colors.red,
            highlightSpotColor: Theme.colors.yellow
          });
        });
    }

    /*-----------------------------------------------------------------------------------*/
    /*  Handles flot charts in dashboard
    /*-----------------------------------------------------------------------------------*/
    var handleDashFlotCharts = function () {
        function chartMonth() { 
            var data1 = [[0, 1.5],[1, 2], [2, 1], [3, 1.5], [4, 2.5],[5, 2], [6, 2], [7, 0.5], [8, 1], [9, 1.5], [10, 2],[11, 2.5], [12, 2], [13, 1.5], [14, 2.8], [15, 2],[16, 3], [17, 2], [18, 2.5], [19, 3],[20, 2.5], [21, 2], [22, 1.5], [23, 2.5], [24, 2], [25, 1.5],[26, 1], [27, 0.5], [28, 1], [29, 1],[30, 1.5], [31, 1]];
            var data2 = [[0, 2.5],[1, 3.5], [2, 2], [3, 3], [4, 4],[5, 3.5], [6, 3.5], [7, 1], [8, 2], [9, 3], [10, 4],[11, 5], [12, 4], [13, 3], [14, 5], [15, 3.5],[16, 5], [17, 4], [18, 5], [19, 6],[20, 5], [21, 4], [22, 3], [23, 5], [24, 4], [25, 3],[26, 2], [27, 1], [28, 2], [29, 2],[30, 3], [31, 2]];
            
            var plot = $.plot($("#chart-dash"), [{
                data: data2,
                label: "Pageviews",
                bars: {
                    show: true,
                    fill: true,
                    barWidth: 0.4,
                    align: "center",
                    lineWidth: 13
                }
            }, {
                data: data1,
                label: "Visits",
                lines: {
                    show: true,
                    lineWidth: 2
                },
                points: {
                    show: true,
                    lineWidth: 2,
                    fill: true
                },
                shadowSize: 0
            }, {
                data: data1,
                label: "Visits",
                lines: {
                    show: true,
                    lineWidth: 1,
                    fill: true,
                    fillColor: {
                        colors: [{
                                opacity: 0.05
                            }, {
                                opacity: 0.01
                            }
                        ]
                    }
                },
                points: {
                    show: true,
                    lineWidth: 0.5,
                    fill: true
                },
                shadowSize: 0
            }], {
                grid: {
                    hoverable: true,
                    clickable: true,
                    tickColor: "#f7f7f7",
                    borderWidth: 0,
                    labelMargin: 10,
                    margin: {
                        top: 0,
                        left: 5,
                        bottom: 0,
                        right: 0
                    }
                },
                legend: {
                    show: false
                },
                colors: ["rgba(109,173,189,0.5)", "#70AFC4", "#DB5E8C"],
                
                xaxis: {
                    ticks: 5,
                    tickDecimals: 0,
                    tickColor: "#fff"
                },
                yaxis: {
                    ticks: 3,
                    tickDecimals: 0
                },
            });
            function showTooltip(x, y, contents) {
                    $('<div id="tooltip">' + contents + '</div>').css({
                            position: 'absolute',
                            display: 'none',
                            top: y + 5,
                            left: x + 15,
                            border: '1px solid #333',
                            padding: '4px',
                            color: '#fff',
                            'border-radius': '3px',
                            'background-color': '#333',
                            opacity: 0.80
                        }).appendTo("body").fadeIn(200);
                }
            var previousPoint = null;
            $("#chart-dash").bind("plothover", function (event, pos, item) {
                $("#x").text(pos.x.toFixed(2));
                $("#y").text(pos.y.toFixed(2));
                if (item) {
                    if (previousPoint != item.dataIndex) {
                        previousPoint = item.dataIndex;
                        $("#tooltip").remove();
                        var x = item.datapoint[0].toFixed(2),
                            y = item.datapoint[1].toFixed(2);
                        showTooltip(item.pageX, item.pageY,
                            item.series.label + " of " + x + " = " + y);
                    }
                } else {
                    $("#tooltip").remove();
                    previousPoint = null;
                }
            });
        }
        
        //Select chart
        function chart_select() {
                // setup plot
                function getData(x1, x2) {

                    var d = [];
                    for (var i = 0; i <= 100; ++i) {
                        var x = x1 + i * (x2 - x1) / 100;
                        d.push([x, Math.cos(x * Math.sin(x))]);
                    }

                    return [
                        { label: "cos(x sin(x))", data: d }
                    ];
                }

                var options = {
                    grid: {
                        hoverable: true,
                        clickable: true,
                        tickColor: "#f7f7f7",
                        borderWidth: 0,
                        labelMargin: 10,
                        margin: {
                            top: 0,
                            left: 5,
                            bottom: 0,
                            right: 0
                        }
                    },
                    legend: {
                        show: false
                    },
                    series: {
                        lines: {
                            show: true
                        },
                        shadowSize: 0,
                        points: {
                            show: true
                        }
                    },
                    colors: ["#D9534F"],
                    yaxis: {
                        ticks: 10
                    },
                    selection: {
                        mode: "xy",
                        color: "#F1ADAC"
                    }
                };

                var startData = getData(0, 3 * Math.PI);

                var plot = $.plot("#placeholder", startData, options);

                // Create the overview plot

                var overview = $.plot($("#overview"), startData, {
                    legend: {
                        show: false
                    },
                    series: {
                        lines: {
                            show: true,
                            lineWidth: 1
                        },
                        shadowSize: 0
                    },
                    xaxis: {
                        ticks: 4
                    },
                    yaxis: {
                        ticks: 3,
                        min: -2,
                        max: 2
                    },
                    colors: ["#D9534F"],
                    grid: {
                        color: "#999",
                        borderWidth: 0,
                    },
                    selection: {
                        mode: "xy",
                        color: "#F1ADAC"
                    }
                });

                // now connect the two

                $("#placeholder").bind("plotselected", function (event, ranges) {

                    // clamp the zooming to prevent eternal zoom

                    if (ranges.xaxis.to - ranges.xaxis.from < 0.00001) {
                        ranges.xaxis.to = ranges.xaxis.from + 0.00001;
                    }

                    if (ranges.yaxis.to - ranges.yaxis.from < 0.00001) {
                        ranges.yaxis.to = ranges.yaxis.from + 0.00001;
                    }

                    // do the zooming

                    plot = $.plot("#placeholder", getData(ranges.xaxis.from, ranges.xaxis.to),
                        $.extend(true, {}, options, {
                            xaxis: { min: ranges.xaxis.from, max: ranges.xaxis.to },
                            yaxis: { min: ranges.yaxis.from, max: ranges.yaxis.to }
                        })
                    );

                    // don't fire event on the overview to prevent eternal loop

                    overview.setSelection(ranges, true);
                });

                $("#overview").bind("plotselected", function (event, ranges) {
                    plot.setSelection(ranges);
                });

                // Add the Flot version string to the footer

                $("#footer").prepend("Flot " + $.plot.version + " &ndash; ");

        }
        
        //Revenue chart
        function chart_revenue() {
            var likes = [[1, Math.random()*100], [2, Math.random()*100], [3, Math.random()*100], [4, Math.random()*100],[5,Math.random()*100],[6, Math.random()*100],[7, Math.random()*100],[8, Math.random()*100],[9, Math.random()*100],[10, Math.random()*100],[11, Math.random()*100],[12, Math.random()*100]];
        
            var chartColor = $(this).parent().parent().css("color");
            
            var plot = $.plot($("#chart-revenue"),
                   [ { data: likes} ], {
                       series: {
                           label: "Revenue",
                           lines: { 
                                show: true,
                                lineWidth: 3, 
                                fill: false
                           },
                           points: { 
                                show: true, 
                                lineWidth: 3,
                                fill: true,
                                fillColor: chartColor 
                           },   
                           shadowSize: 0
                       },
                       grid: { hoverable: true, 
                               clickable: true, 
                               tickColor: "rgba(255,255,255,.15)",
                               borderColor: "rgba(255,255,255,0)"
                             },
                       colors: ["#fff"],
                       xaxis: {
                            font: {
                                color: "#fff"
                            },
                            ticks:6, 
                            tickDecimals: 0, 
                            tickColor: chartColor,
                       },
                       yaxis: {
                            font: {
                                color: "#fff"
                            },
                            ticks:4, 
                            tickDecimals: 0,
                            autoscaleMargin: 0.000001
                       },
                       legend: {
                            show: false
                       }
                     });

            function showTooltip(x, y, contents) {
                $('<div id="tooltip">' + contents + '</div>').css( {
                    position: 'absolute',
                    display: 'none',
                    top: y + 5,
                    left: x + 5,
                    border: '1px solid #fdd',
                    padding: '2px',
                    'background-color': '#dfeffc',
                    opacity: 0.80
                }).appendTo("body").fadeIn(200);
            }

            var previousPoint = null;
            $("#chart-revenue").bind("plothover", function (event, pos, item) {
                $("#x").text(pos.x.toFixed(2));
                $("#y").text(pos.y.toFixed(2));

                    if (item) {
                        if (previousPoint != item.dataIndex) {
                            previousPoint = item.dataIndex;

                            $("#tooltip").remove();
                            var x = item.datapoint[0].toFixed(2),
                                y = item.datapoint[1].toFixed(2);

                            showTooltip(item.pageX, item.pageY,
                                        item.series.label + " on " + x + " = " + y);
                        }
                    }
                    else {
                        $("#tooltip").remove();
                        previousPoint = null;
                    }
            });
        }
        
        //Run the charts
        chartMonth();
        chart_select();
        chart_revenue();
        
        //Pie 1
        $('#dash_pie_1').easyPieChart({
            easing: 'easeOutBounce',
            onStep: function(from, to, percent) {
                $(this.el).find('.percent').text(Math.round(percent)+"%");
            },
            lineWidth: 6,
            barColor: Theme.colors.purple
        });
        var chart1 = window.chart = $('#dash_pie_1').data('easyPieChart');
        //Pie 2
        $('#dash_pie_2').easyPieChart({
            easing: 'easeOutBounce',
            onStep: function(from, to, percent) {
                $(this.el).find('.percent').text(Math.round(percent)+"%");
            },
            lineWidth: 6,
            barColor: Theme.colors.yellow
        });
        var chart2 = window.chart = $('#dash_pie_2').data('easyPieChart');
        //Pie 3
        $('#dash_pie_3').easyPieChart({
            easing: 'easeOutBounce',
            onStep: function(from, to, percent) {
                $(this.el).find('.percent').text(Math.round(percent)+"%");
            },
            lineWidth: 6,
            barColor: Theme.colors.pink
        });
        var chart3 = window.chart = $('#dash_pie_3').data('easyPieChart');
        
        //Update the charts
        $('.js_update').on('click', function() {
            chart1.update(Math.random()*100);
            chart2.update(Math.random()*100);
            chart3.update(Math.random()*100);
            chart_revenue();
        });
    }

    /*-----------------------------------------------------------------------------------*/
    /*  Handles Gritter on Load
    /*-----------------------------------------------------------------------------------*/
    var handleGritter = function () {
        if ($.cookie('gritter_show')) {
                return;
            }

            $.cookie('gritter_show', 1);
            setTimeout(function () {
                var unique_id = $.gritter.add({
                    // (string | mandatory) the heading of the notification
                    title: 'Xin chào XXXXXXXX!',
                    // (string | mandatory) the text inside the notification
                    text: 'Tài khoản của bạn sẽ hết hạn trong XXX ngày nữa',
                    // (string | optional) the image to display on the left
                    image: 'img/gritter/cloud.png',
                    // (bool | optional) if you want it to fade out on its own or just sit there
                    sticky: true,
                    // (int | optional) the time you want it to be alive for before fading out
                    time: '',
                    // (string | optional) the class name you want to apply to that specific message
                    class_name: 'my-sticky-class'
                });

                // You can have it return a unique id, this can be used to manually remove it later using
                setTimeout(function () {
                    $.gritter.remove(unique_id, {
                        fade: true,
                        speed: 'slow'
                    });
                }, 12000);
            }, 2000);

            setTimeout(function () {
                var unique_id = $.gritter.add({
                    // (string | mandatory) the heading of the notification
                    title: 'Customize Cloud Admin!',
                    // (string | mandatory) the text inside the notification
                    text: 'Cloud Admin is easily customizable, lightweight and has a great User Experience.',
                    // (string | optional) the image to display on the left
                    image: 'img/gritter/settings.png',
                    // (bool | optional) if you want it to fade out on its own or just sit there
                    sticky: true,
                    // (int | optional) the time you want it to be alive for before fading out
                    time: '',
                    // (string | optional) the class name you want to apply to that specific message
                    class_name: 'my-sticky-class'
                });

                // You can have it return a unique id, this can be used to manually remove it later using
                setTimeout(function () {
                    $.gritter.remove(unique_id, {
                        fade: true,
                        speed: 'slow'
                    });
                }, 13000);
            }, 8000);

            setTimeout(function () {

                $.extend($.gritter.options, {
                    position: 'top-left'
                });

                var unique_id = $.gritter.add({
                    position: 'top-left',
                    // (string | mandatory) the heading of the notification
                    title: 'Chào mừng bạn đến với Khảo sát việt!',
                    // (string | mandatory) the text inside the notification
                    text: 'Phần mềm ứng dụng khảo sát online uy tín hàng đầu Việt Nam!',
                    // (string | optional) the image to display on the left
                    image: 'img/gritter/buy.png',
                    // (bool | optional) if you want it to fade out on its own or just sit there
                    sticky: true,
                    // (int | optional) the time you want it to be alive for before fading out
                    time: '',
                    // (string | optional) the class name you want to apply to that specific message
                    class_name: 'my-sticky-class'
                });

                $.extend($.gritter.options, {
                    position: 'top-right'
                });

                // You can have it return a unique id, this can be used to manually remove it later using
                setTimeout(function () {
                    $.gritter.remove(unique_id, {
                        fade: true,
                        speed: 'slow'
                    });
                }, 15000);

            }, 15000);

            setTimeout(function () {

                $.extend($.gritter.options, {
                    position: 'top-left'
                });

                var unique_id = $.gritter.add({
                    // (string | mandatory) the heading of the notification
                    title: 'Notification',
                    // (string | mandatory) the text inside the notification
                    text: 'You have 6 new notifications.',
                    // (bool | optional) if you want it to fade out on its own or just sit there
                    sticky: true,
                    // (int | optional) the time you want it to be alive for before fading out
                    time: '',
                    // (string | optional) the class name you want to apply to that specific message
                    class_name: 'my-sticky-class'
                });

                setTimeout(function () {
                    $.gritter.remove(unique_id, {
                        fade: true,
                        speed: 'slow'
                    });
                }, 4000);

                $.extend($.gritter.options, {
                    position: 'top-right'
                });

            }, 20000);

            setTimeout(function () {

                $.extend($.gritter.options, {
                    position: 'top-left'
                });

                var unique_id = $.gritter.add({
                    // (string | mandatory) the heading of the notification
                    title: 'Inbox',
                    // (string | mandatory) the text inside the notification
                    text: 'You have 5 new messages in your inbox.',
                    // (bool | optional) if you want it to fade out on its own or just sit there
                    sticky: true,
                    // (int | optional) the time you want it to be alive for before fading out
                    time: '',
                    // (string | optional) the class name you want to apply to that specific message
                    class_name: 'my-sticky-class'
                });

                $.extend($.gritter.options, {
                    position: 'top-right'
                });

                setTimeout(function () {
                    $.gritter.remove(unique_id, {
                        fade: true,
                        speed: 'slow'
                    });
                }, 4000);

            }, 25000);
    }

    /*-----------------------------------------------------------------------------------*/
    /*  Data Tables
    /*-----------------------------------------------------------------------------------*/
    var handleDataTables = function () {
        $('#datatable1').dataTable({
                "sPaginationType": "bs_full"
            });
        $('#datatable2').dataTable({
                "sPaginationType": "bs_full",
                sDom: "<'row'<'dataTables_header clearfix'<'col-md-4'l><'col-md-8'Tf>r>>t<'row'<'dataTables_footer clearfix'<'col-md-6'i><'col-md-6'p>>>",
                oTableTools: {
                    aButtons: ["copy", "print", "csv", "xls", "pdf"],
                    sSwfPath: "js/datatables/extras/TableTools/media/swf/copy_csv_xls_pdf.swf"
                }
            });
        $('.datatable').each(function(){
            var datatable = $(this);
            // SEARCH - Add the placeholder for Search and Turn this into in-line form control
            var search_input = datatable.closest('.dataTables_wrapper').find('div[id$=_filter] input');
            search_input.attr('placeholder', 'Tìm kiếm');
            search_input.addClass('form-control input-sm');
            // LENGTH - Inline-Form control
            var length_sel = datatable.closest('.dataTables_wrapper').find('div[id$=_length] select');
            length_sel.addClass('form-control input-sm');
        });
    }

    /*handle project in table */
    var handleProjectInTable = function(){
        $("div.hidd").css('display','none');
        $(".hov").mouseover(function() {
          var id = $(this).closest('tr').attr('id'); 
          $("#"+id+" .hidd").removeClass('abc123');
          $("#"+id+" .hidd").css('display','block'); 
        });
        $(".hov").mouseout(function() { 
          var id = $(this).closest('tr').attr('id'); 
          $("#"+id+" .hidd").css('display','none'); 
          $("#"+id+" .hidd").addClass('abc123');
        }); 
     
        /*del project*/
        $('.del').on('click', function(e) {
            e.preventDefault();
            var id = $(this).data('id');
            $('#alert-del').data('id', id).modal('show');
        });

        $('#btnYes').click(function() {
            var id = $('#alert-del').data('id');
            $('#alert-del').modal('hide');
            var data = 'id=' + id ;
            $.ajax(
            {
                 type: "POST",
                 url: "<?php echo site_url('member/createSurvey/ajaxDelProject');?>",
                 data: data,
                 cache: false,
              
                 success: function(rs)
                 {
                  if(rs=='1'){
                      $('#project'+id).fadeOut('slow', function() {$(this).remove();});
                  }else{
                    alert('Lỗi trong quá trình xóa dự án');
                  }
                }
             }); 
        });
    }
	
	return {

        //Initialise theme pages
        init: function () {
            if (App.isPage("home")) {
                handleDateTimePickers(); //Function to display Date Timepicker
                handleSparkline();      //Function to display Sparkline charts
                handleDashFlotCharts(); //Function to display flot charts in dashboard
                handleGritter();    //Function to display Gritter notifications
                handleDataTables(); //Function to display data tables
                handleProjectInTable(); // Function to process project in table
            }
            checkLayout();  //Function to check if mini menu/fixed header is activated
            handleSidebar(); //Function to display the sidebar
            handleSidebarCollapse(); //Function to hide or show sidebar
            handleSidebarAndContentHeight();  //Function to hide sidebar and main content height
            responsiveSidebar();        //Function to handle sidebar responsively
            handleTeamView(); //Function to toggle team view
            handleHomePageTooltips(); //Function to handle tooltips
            handleBoxTools(); //Function to handle box tools
            handleSlimScrolls(); //Function to handle slim scrolls
            handlePopovers(); //Function to handle popovers
            handleMessenger(); //Function to handle messenger
            handleAlerts(); //Function to handle alerts
            handleCustomTabs(); //Function to handle min-height of custom tabs
            handleGoToTop();    //Funtion to handle goto top buttons
            handleNavbarFixedTop();     //Function to check & handle if navbar is fixed top
            //handleThemeSkins();     //Function to handle theme skins
        },

        // set theme path
        setThemePath: function(path) {
            themePath = path;
        },

        //Set page
        setPage: function (name) {
            currentPage = name;
        },

        isPage: function (name) {
            return currentPage == name ? true : false;
        },
        //public function to add callback a function which will be called on window resize
        addResponsiveFunction: function (func) {
            responsiveFunctions.push(func);
        },
        // wrapper function to scroll(focus) to an element
        scrollTo: function (el, offeset) {
            pos = (el && el.size() > 0) ? el.offset().top : 0;
            jQuery('html,body').animate({
                scrollTop: pos + (offeset ? offeset : 0)
            }, 'slow');
        },

        // function to scroll to the top
        scrollTop: function () {
            App.scrollTo();
        },
        // initializes uniform elements
        initUniform: function (els) {
            if (els) {
                jQuery(els).each(function () {
                    if ($(this).parents(".checker").size() == 0) {
                        $(this).show();
                        $(this).uniform();
                    }
                });
            } else {
                handleAllUniform();
            }
        },
        // wrapper function to  block element(indicate loading)
        blockUI: function (el, loaderOnTop) {
            lastBlockedUI = el;
            jQuery(el).block({
                message: '<img src="./img/loaders/12.gif" align="absmiddle">',
                css: {
                    border: 'none',
                    padding: '2px',
                    backgroundColor: 'none'
                },
                overlayCSS: {
                    backgroundColor: '#000',
                    opacity: 0.05,
                    cursor: 'wait'
                }
            });
        },

        // wrapper function to  un-block element(finish loading)
        unblockUI: function (el) {
            jQuery(el).unblock({
                onUnblock: function () {
                    jQuery(el).removeAttr("style");
                }
            });
        },
    };
}();

(function () {
    this.Theme = (function () {
        function Theme() {}
        Theme.colors = {
            white: "#FFFFFF",
            primary: "#5E87B0",
            red: "#D9534F",
            green: "#A8BC7B",
            blue: "#70AFC4",
            orange: "#F0AD4E",
            yellow: "#FCD76A",
            gray: "#6B787F",
            lightBlue: "#D4E5DE",
            purple: "#A696CE",
            pink: "#DB5E8C",
            dark_orange: "#F38630"
        };
        return Theme;
    })();
})(window.jQuery);
